/**
 * 
 */
package org.swing.utility.common.chars;

import io.netty.buffer.ByteBuf;

/**
 * @author lqnhu
 *
 */
public class ReadOnlyAsciiBuf extends ReadOnlyUtfBuf {
	public ReadOnlyAsciiBuf(ByteBuf data) {
		super(data);
	}

	public ReadOnlyAsciiBuf(CharBuf charBuf) {
		super(charBuf.toByteBuf());
	}

	
	protected boolean knownAsciiOnly(int cacheInstance) {
		return true;
	}

	
	public int length() {
		return getByteLength();
	}

	
	public char charAt(int index) {
		return (char) getByte(index);
	}

	// start is inclusive, end is exclusive
	
	public ReadableCharBuf subSequence(int start, int end) {
		return getSubSequenceForByteBounds(start, end);
	}

	/**
	 * Uses the cacheInstance for the hashCache (cacheHash? whichever dumb name
	 * Donnelly wanted)
	 */
	
	public int hashCode() {
		int hash = packedIndexCache;
		if (hash == 0) {
			int length = length();
			for (int i = 0; i < length; i++) {
				char c = charAt(i);
				hash = 31 * hash + c;
			}
			packedIndexCache = hash;
		}
		return hash;
	}

	
	public String toString() {
		// TODO: if our ByteBuf has a backing array, then we can use the
		// deprecated, ascii-only
		// String constructor : new String(byte[], int, int, int)
		// Can't find a good way around String's stupid always-copy constructor,
		// but by
		// not using content().toString(UTF8), we can at least prevent one extra
		// allocation.
		//
		// ((CharBuffer alloc, CharBuffer toString, new String) -> (char[]
		// alloc, new String))
		//
		// If desperate, _might_ be able to hack it with a dummy
		// CharacterEncoder if there is
		// no security manager. Otherwise have to class path boot etc to get
		// into the lang
		// package. I suppose annoyances like these are why I made this package.
		ByteBuf slice = content().slice();
		char[] values = new char[slice.capacity()];
		if (slice.readableBytes() > 0) {
			for (int i = 0; i < slice.capacity(); i++) {
				values[i] = (char) slice.getByte(i);
			}
		} else {
			return "";
		}
		return new String(values);
	}
}
